<?php

namespace App\Admin\Forms;

use App\Models\ObjectStorageService;
use App\Models\Version;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Exception\RuntimeException;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use PhpZip\Exception\ZipException;
use PhpZip\ZipFile;

class UpdateVersionForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input): JsonResponse
    {
        $bucket = $input['bucket'];
        $oss = ObjectStorageService::ofAdmin()->find($bucket);
        $version = Version::find($this->payload['version_id']);

        $zip = new ZipFile();
        try {
            $zip->openFromString(request()->application->domainPool->storage()->get($version->file), [
                'charset' => 'cp936',
            ]);
            foreach ($zip->getListFiles() as $entryName) {
                if ($zip->isDirectory($entryName)) {
                    continue;
                }
                $contents = $zip->getEntryContents($entryName);
                $oss->storage()->put($entryName, $contents);
            }

            $version->logs()->create([
                'admin_id' => Admin::user()->id,
                'object_storage_service_id' => $oss->id,
                'bucket' => $oss->bucket,
            ]);

            return $this->response()->success('版本发布成功')->refresh();
        } catch (ZipException $e) {
            return $this->response()->error($e->getMessage());
        }
    }

    /**
     * @throws RuntimeException
     */
    public function form(): void
    {
        $this->select('bucket', '发布空间(存储桶)')
            ->width(6, 4)
            ->required()
            ->options(
                ObjectStorageService::ofAdmin()
                    ->where('type', $this->payload['type'])
                    ->pluck('bucket', 'id')
            );
    }
}
